﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

namespace MapEditor.Model
{
    /// <summary>
    /// Get all game Item from define file
    /// </summary>
    public class GameItemCollection : ObservableCollection<GameItem>
    {
        //private const string GAME_ITEM_FILE = @"GameData\Map_1.txt";
        private const string IMAGE_FILE = @"Images\";

        public GameItemCollection()
        {
            //GetGameItemFromFile(GAME_ITEM_FILE);
        }

        public GameItemCollection(string GameItemFile)
        {
            GetGameItemFromFile(GameItemFile);
        }

        /// <summary>
        /// Update list item from another file
        /// </summary>
        /// <param name="FileName"></param>
        public ObservableCollection<GameItem> UpdateGameItems(string FileName)
        {
            this.Clear();
            this.GetGameItemFromFile(FileName);

            return this;
        }


        /// <summary>
        /// Get list game item from txt file
        /// </summary>
        /// <param name="FileName"></param>
        private void GetGameItemFromFile(string FileName)
        {
            using (StreamReader reader = new StreamReader(FileName))
            {
                //get images directory
                DirectoryInfo imagesDInfo = new DirectoryInfo(IMAGE_FILE);

                string line;
                int itemType = 0;
                string itemName = "";
                string imageIcon = "";
                Bitmap itemImage;
                double Width = 0;
                double Height = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    var itemData = line.Split(' ');
                    if (itemData.Count() >= 5)
                    {
                        itemType = int.Parse(itemData[0]);
                        itemName = itemData[1];
                        imageIcon = IMAGE_FILE + itemData[2];
                        
                        try
                        {
                            itemImage = new Bitmap((imagesDInfo.FullName + itemData[2]).ToString());
                        }
                        catch
                        {
                            //Get default emage
                            itemImage = new Bitmap((imagesDInfo.FullName + itemData[2]).ToString());
                        }
                        
                        Width = double.Parse(itemData[3]);
                        Height = double.Parse(itemData[4]);

                        this.Add(new GameItem(itemType, itemName, imageIcon, itemImage,Width,Height));
                    }
                }
            }
        }
    }
}
